package com.isunland.managesystem.utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.VersionUpdate;
import com.isunland.managesystem.ui.UpdateDialogFragment;
import java.io.File;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 更新工具类
 * Created by wangyanan on 2016/9/28.
 */
public class UpdateUtil {
  private static final int notificationID = 1;
  private static final int REQUEST_SHOW_UPDATE = 3;
  private static BaseVolleyActivity mActivity;
  private static Fragment mFragment;
  private static VersionUpdate mVersion;
  private static long mTotalByte;
  private static UpdateUtil mUtil;
  private static boolean isShow;//是否显示等待视图，和提示信息（如当前是最新版本）
  private String filePath = "";
  private NotificationManager mNotificationManager;
  private File mAPKFile;
  private Notification mNotification;

  /**
   * @param fragment 当前Fragment
   * @param isShowLoading 是否显示等待视图
   */
  public static void update(Fragment fragment, boolean isShowLoading) {
    mFragment = fragment;
    isShow = isShowLoading;
    mActivity = (BaseVolleyActivity) fragment.getActivity();
    if (isShowLoading) {

      MyUtils.showDialogLoading(mActivity);
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LATEST_VERSION);
    HashMap<String, String> params = new HashMap<>();
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        handleResponseUpdate(arg0);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  private static void handleResponseUpdate(String jsonString) {
    try {
      LogUtil.i("response=" + jsonString);
      mVersion = new Gson().fromJson(jsonString, VersionUpdate.class);
      if (mVersion == null) {
        return;
      }
      int currentVersion =
          mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0).versionCode;

      if ((mVersion.getVerCode() <= currentVersion)) {
        if (isShow) {

          Toast.makeText(mActivity, R.string.latest_version, Toast.LENGTH_SHORT).show();
        }
        return;
      }

      mTotalByte = mVersion.getTotalByte();
      showDialog(REQUEST_SHOW_UPDATE);
    } catch (Exception e) {
      e.printStackTrace();

      LogUtil.e("e=" + e.toString(), e);
    }
  }

  private static void showDialog(int type) {
    FragmentManager fm = mActivity.getSupportFragmentManager();
    DialogFragment dialog = UpdateDialogFragment.newInstance(mVersion);
    if (dialog == null) return;
    dialog.setTargetFragment(mFragment, type);
    dialog.show(fm, "");
  }
}
